package com.zhangfei.monitor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Component
public class ThreadPoolMonitor extends ThreadPoolTaskExecutor {

    @Value("${async.executor.thread.name.prefix}")
    private String namePrefix;

    @Scheduled(cron = "0/1 * * * * ? ")
    private void showThreadPoolInfo() {
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        log.info("monitor:"+this.getThreadNamePrefix());
        log.info("namePrefix:"+namePrefix);
        if ("threadPoolMonitor-".equals(this.getThreadNamePrefix())){
            log.info("{} taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]",
                    this.getThreadNamePrefix(),
                    threadPoolExecutor.getTaskCount(),
                    threadPoolExecutor.getCompletedTaskCount(),
                    threadPoolExecutor.getActiveCount(),
                    threadPoolExecutor.getQueue().size());
        }
    }
}
